<?php

namespace app\daren\controller\admin\job;

use app\operations\model\Store;
use sheep\controller\Backend;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;
use app\daren\model\job\NewJob as NewJobModel;
use app\daren\validate\admin\job\NewJob as NewJobValidate;

// 商品任务
class NewJob extends Backend
{
    public $organ_id;

    public function initialize()
    {
        $this->organ_id = $this->shopId();
        $this->model = new NewJobModel;
    }

    /**
     * 商品列表
     *
     * @return \think\Response
     */
    public function list(Request $request)
    {
        $user = $this->auth()->user();
        $store_id = $this->shopId();
        $param = $request->param();
        if ($user->role_id != 1) {
            $param['store_id'] = $store_id;
        }
        $daren = $this->model->getList($param);
        return success('获取成功', $daren);
    }

    // 添加
    public function add(Request $request)
    {
        $param = $request->only([
            'title', 'tag', 'title_cover_image', 'activity_time', 'end_time', 'start_time', 'is_cloud', 'take_material', 'day_times', 'cloud_number', 'cloud_fee', 'platform_require', 'work_form', 'province_limit', 'other_require', 'store_id', 'link', 'mobile', 'poiId', 'selling_point', 'shop_address','goods'
        ]);
        $param['activity_time'] = strtotime($param['activity_time']);
        $param['start_time'] = strtotime($param['start_time']);
        $param['end_time'] = strtotime($param['end_time']);

//        try {
//            validate(NewJobValidate::class)
//                ->scene('add')
//                ->check($param);
//        } catch (ValidateException $e) {
//            // 验证失败 输出错误信息
//            return error($e->getError());
//        }
        $user              = $this->auth()->user();
        if ($user->role_id != 1) {
            $param['organ_id'] = $user->organ_id;
            $param['store_id'] = $this->organ_id;
        } else {
            $store_data = Store::where(['id' => $param['store_id']])->findOrEmpty();
            $param['organ_id'] = $store_data['organ_id'];
        }

        $jobResult = $this->model->insertGetId($param);
//        $jobResult = $this->model->dataCreate($param); // 插入并获取任务ID
        if (!$jobResult) {
            return error('保存失败');
        }



        if($param['tag']==3){
            // 处理 goods 字符串，将其转换为数组
            $goodsIds = explode(',', $param['goods']);  // 将逗号分隔的字符串转换为数组

            // 插入任务和商品的关联
            foreach ($goodsIds as $goodsId) {
                // 准备插入的任务与商品关联数据
                $jobGoodsData = [
                    'job_id' => $jobResult,  // 新任务的ID
                    'goods_id'   => $goodsId      // 商品的ID
                ];


                // 插入到当前数据库的中间表
                $this->model->table('saas_new_job_goods')->insert($jobGoodsData);

                // 同步到萌宠霸王数据库的中间表
                $cutepetDb = Db::connect('mysql_cutepet');
                $cutepetJobData = [
                    'job_id' => $jobResult,
                    'goods_id'   => $goodsId
                ];

                // 插入到萌宠霸王的中间表
                $cutepetJobInsert = $cutepetDb->name('new_job_goods')->insert($cutepetJobData);

                // 如果同步失败，返回错误
                if (!$cutepetJobInsert) {
                    return error('同步萌宠霸王失败');
                }
            }
        }



        // 同步萌宠霸王

        $param['external_id'] = $jobResult;
        $param['create_time']         = time();
        $param['update_time']         = time();
        $cutepetDb                    = Db::connect('mysql_cutepet');
        $cutepetGroupGoods            = $cutepetDb->name('new_job')->insert($param);
        if (!$cutepetGroupGoods) {
            return error('同步萌宠霸王失败');
        }

        return success('保存成功');
    }

    /**
     * 商品详情
     *
     * @return \think\Response
     */
    public function detail(Request $request, $id)
    {
        $goods = $this->model->detail($id);
        if ($goods->isEmpty()) {
            return error('商品任务不存在');
        }
        $goods_ids = explode(',', $goods['goods']);
        $goods_datas = Db::name('shop_goods')->whereIn('id', $goods_ids)->select()->toArray();
        $goods['goods'] = $goods_datas ?: [];
        return success('获取成功', $goods);
    }

    // 审核
    public function statusEdit(Request $request)
    {
        $param = $request->only([
            'id', 'status', 'remark'
        ]);
        if (empty($param['id']) || empty($param['status'])) {
            return error('参数有误');
        }
        $user = $this->auth()->user();
        $daren = $this->model->detail($param['id']);
        if ($daren->isEmpty()) {
            return error('商品任务不存在');
        }
        if ($daren->status['value'] != 1) {
            return error('该商品任务已审核');
        }

        $result = $this->model->dataStatusEdit($param);
        if (!$result) {
            return error('修改失败');
        }

        // 同步萌宠霸王
        $id = $result->id;
        unset($param['id']);
//        $param['pass_time']  = time();

        $cutepetDb             = Db::connect('mysql_cutepet');
        $cutepetGroupGoods     = $cutepetDb->name('new_job')->where('external_id', $id)->update($param);
        if (!$cutepetGroupGoods) {
            return error('同步萌宠霸王失败');
        }

        return success('审核成功');
    }

    // 上下架
    public function shelfStatusEdit(Request $request)
    {
        $param = $request->only([
            'id', 'shelf_status'
        ]);
        if (empty($param['id']) || empty($param['shelf_status'])) {
            return error('参数有误');
        }
        $user = $this->auth()->user();
        if ($param['shelf_status'] == 1) {
            $param['start_time'] = time();
        }

        $result = $this->model->shelfStatusEdit($param);
        if (!$result) {
            return error('修改失败');
        }

        // 同步萌宠霸王
        $id = $result->id;
        unset($param['id']);
//        $param['pass_time']  = time();

        $cutepetDb             = Db::connect('mysql_cutepet');
        $cutepetGroupGoods     = $cutepetDb->name('new_job')->where('external_id', $id)->update($param);
        if (!$cutepetGroupGoods) {
            return error('同步萌宠霸王失败');
        }

        return success('成功');
    }

    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function delete($id)
    {
        if (empty($id))
        {
            return error('参数有误');
        }
        $result = $this->model->deleteData($id);
        if (!$result) {
            return error('删除失败');
        }
        // 同步萌宠霸王
        $param['update_time']  = time();
        $param['delete_time']  = time();

        $cutepetDb             = Db::connect('mysql_cutepet');
        $cutepetGroupGoods     = $cutepetDb->name('new_job')->where('external_id', $id)->update($param);
        if (!$cutepetGroupGoods) {
            return error('同步萌宠霸王失败');
        }

        return success('删除成功');
    }
}